<?php
namespace app\admin\controller;

use app\common\controller\Common;
use think\Controller;
use think\Loader;
use think\Request;
use think\Url;
use think\Session;
use think\Config;
use think\Db;

/**
* 登录
* @author aierui github  https://github.com/Aierui
* @version 1.0 
*/
class Login extends Common
{
	/**
	 * 后台登录首页
	 */
	public function index()
	{

		if( Session::has('userinfo', 'admin') ) {
			$this->redirect( url('admin/index/index') );
		}
		return view();
	}

	/**
	 * 登录验证
	 */
	public function doLogin()
	{
		if( !Request::instance()->isAjax() ) {
			$this->success( lang('Request type error') );
		}

		$postData = input('post.');
		//验证码
		$captcha = $postData['captcha'];
		if(!captcha_check($captcha)){
			$this->error( lang('Captcha error') );
		};

		$loginData = array(
			'username'=>$postData['username'],
			'password'=>$postData['password']
		);
		$ret = Loader::model('User')->login( $loginData );

		if ($ret['code'] !== 1) {
			$this->error( $ret['msg'] );
		}
		unset($ret['data']['password']);
		Session::set('userinfo' , $ret['data']->toArray() , 'admin');
		Loader::model('LogRecord')->record( lang('Login succeed') );
		$this->success($ret['msg'], url('admin/index/index'));
	}

	/**
	 * 退出登录
	 */
	public function out()
	{
		session::clear(null);
		$this->success(lang('Logout success'), url('admin/login/index'));
	}


	/**
     * 注册
     */
    public function register(){
    	

    	if($this->request->isGet())
    	{
    		$share = $this->request->get();
    		if(isset($share['left']))
    		{
    			session('share',$share['left']);
    			session('belong','left');
    		}

    		if(isset($share['right']))
    		{
    			session('share',$share['right']);
    			session('belong','right');
    		}
    		$share_user=Db::name('user')->where('eth',session('share'))->find();
    		if(!$share_user)
    		{
    			//跳转到登录页面
            	$this->redirect("/");
    		}
    		$this->assign('share_username',$share_user['username']);
    	}

        if($this->request->isPost()){

            //接受传输参数
            $data = $this->request->post();
            
            if(!session('share'))
            {
            	//跳转到登录页面
            	$this->redirect("/");
            }

            //对session进行校验


            $share_user=Db::name('user')->where('eth',session('share'))->find();
            if(!$share_user)
            {
            	//跳转到登录页面
            	$this->redirect("/");
            }

            

            if(!session('belong'))
            {
            	//跳转到登录页面
            	$this->redirect("/");
            }


            if(session('belong')!='left' and session('belong')!='right')
            {
            	//跳转到登录页面
            	$this->redirect("/");
            }


            //规则验证
            $validate = Loader::validate('Register');
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            //校验用户名是否已经被注册
            $isuser = Db::name('user')->where('username',$data['username'])->find();
            if($isuser)
            {
            	$this->error(info(lang('Username already exists'),0)['msg']);
            }


            //验证确认密码是否相同
            if($data['password'] !== $data['password2']){
                
                $this->error(info(lang('The two passwords No match'),0)['msg']);
            }
            if($data['pay_password'] !== $data['pay_password2']){
                
                $this->error(info(lang('The two paypasswords No match'),0)['msg']);
            }

            //对登录密码和支付密码进行加密

            $data['password'] = mduser( $data['password'] );
            $data['pay_password'] = mduser( $data['pay_password'] );
            /*var_dump(session('belong'));
            print_r($data);exit;*/
            //删除确认密码
            unset($data['password2']);
            unset($data['pay_password2']);
            
            try {
                Db::startTrans();
                //确认交易账号
                $eth_id = Db::name('eth')->where('state = 0')->min('id');
                $eth = Db::name('eth')->where('id',$eth_id)->find();
                $data['eth'] = $eth['eth'];
                $data['share'] = session('share');

                //新增用户
                $res = Db::name('user')->insert($data);
                //更新eth账号被
                $update_state['state'] = 1;
                Db::name('eth')->where('id',$eth_id)->update($update_state);

                //设置左右区
                $belong = session('belong');
                if($belong=='left')
                {
                	$belong_user = $share_user['eth'];
                	if($share_user['left'])
                	{
                		$belong_user = $this->getleft($share_user['left']);

                	}
                	$belong_date['left'] = $data['eth'];
                	Db::name('user')->where('eth',$belong_user)->update($belong_date);
                }

                //设置右区
                if($belong=='right')
                {
                	$belong_user = $share_user['eth'];
                	if($share_user['right'])
                	{
                		$belong_user = $this->getleft($share_user['right']);
                		
                		$belong_date['left'] = $data['eth'];
                		Db::name('user')->where('eth',$belong_user)->update($belong_date);
                	}else
                	{
                		$belong_date['right'] = $data['eth'];
                		Db::name('user')->where('eth',$belong_user)->update($belong_date);
                	}
                }
                Db::commit();



                
            } catch (\Exception $e) 
            {
                Db::rollback();
                
                $this->error(info(lang('Login failed'),0)['msg']);
            }
            $this->success(info(lang('Login success'),0)['msg'],'login/index');

        }else{

            return $this->fetch();     
        }          
    }

    public function getleft($left)
    {
        
        $user = Db::name('user')->where('eth',$left)->find();
        if($user['left'])
        {
            return $this->getleft($user['left']);
        }else
        {
            return $left;
        }
    }
}